# coding=utf-8

"""
    Created by Kalyter on 2017-09-02.
"""

import logging
import os
import sys
from functools import wraps
from logging.handlers import RotatingFileHandler

from .. import __version__ as app


def singleton(cls):
    instances = {}

    @wraps(cls)
    def get_instance(*args, **kw):
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]
    return get_instance


@singleton
class LogUtil(object):
    def __init__(self):
        app_name = app.__title__
        log_format = '[%(asctime)s][%(levelname)s][%(processName)s]' \
                     '[%(threadName)s][%(filename)s(%(lineno)d)] %(message)s'
        formatter = logging.Formatter(log_format)
        # 文件log
        absolute_path = os.getcwd()
        root_path = absolute_path[:absolute_path.index(app_name) + len(app_name)]
        log_path = os.path.join(root_path, 'logs')
        if not os.path.exists(log_path):
            os.makedirs(log_path)
        log_filename = os.path.join(log_path, app_name + '.log')
        max_bytes = 10 * 1024 * 1024 * 1024
        normal_file_adapter = RotatingFileHandler(
            log_filename, maxBytes=max_bytes, backupCount=3, encoding='utf-8')
        normal_file_adapter.setLevel(logging.DEBUG)
        normal_file_adapter.setFormatter(formatter)

        # 错误文件日志
        error_file_path = os.path.join(log_path, '%s.error.log' % app_name)
        error_file_adapter = RotatingFileHandler(
            error_file_path, maxBytes=max_bytes, backupCount=3, encoding='utf-8')
        error_file_adapter.setLevel(logging.ERROR)
        error_file_adapter.setFormatter(formatter)

        # 终端
        console = logging.StreamHandler(sys.stdout)
        console.addFilter(logging.Filter(__name__))
        console.setLevel(logging.DEBUG)
        console.setFormatter(formatter)

        # 注册到logger上
        self.__logger = logging.getLogger(__name__)
        self.__logger.setLevel(logging.DEBUG)
        self.__logger.addHandler(normal_file_adapter)
        self.__logger.addHandler(console)

    @property
    def logger(self):
        return self.__logger


__log_util = LogUtil()


def get_logger():
    return __log_util.logger
